<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="authorityRegister"
    @ok="confirmSubmit"
    @close="drawerReset"
    width="480"
    showFooter
    isAbsolute
    getContainer=".page-wrapper"
  >
    <div class="box-drawer">
      <BasicForm @register="authorityForm">
        <template
          #parentAuthorityId="{ model, field }"
          v-if="treeSelectData.treeData && treeSelectData.treeData.length"
        >
          <a-tree-select
            v-model:value="model[field]"
            :tree-data="treeSelectData.treeData"
            :treeDefaultExpandedKeys="treeSelectData.treeDefaultExpandedKeys"
            @change="treeSelectChange"
            :field-names="{
              label: 'authorityName',
              value: 'authorityId',
              children: 'children'
            }"
          ></a-tree-select>
        </template>
      </BasicForm>
    </div>
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { BasicForm, FormSchema, useForm } from '@/components/Form/index'
import { getAuthorityFormConfig } from '../dataSource'
import { operateActionType } from '@/types/enum'
import { cloneDeep } from 'lodash-es'
import { message } from 'ant-design-vue'
import api from '@/api'

const { authorityAdd, authorityUpdate } = api

const emit = defineEmits(['operateSuccess', 'register'])

const drawerInfo = reactive<any>({
  type: '',
  appId: '',
  selectProductId: '',
  record: {}
})

const treeSelectData = reactive<any>({
  treeData: [],
  treeDefaultExpandedKeys: []
})
const authorityFormConfig = getAuthorityFormConfig()

const [authorityForm, { setFieldsValue, getFieldsValue, validate, resetFields, updateSchema }] =
  useForm(authorityFormConfig)

const [authorityRegister, { closeDrawer, changeOkLoading, changeLoading }] = useDrawerInner(async (data) => {
  drawerInfo.type = data.type
  drawerInfo.appId = data.appId
  drawerInfo.record = cloneDeep(data.record) || {}
  treeSelectData.treeData = cloneDeep(data.treeData)
  console.log(data.treeData, '<=======treeData')
  treeSelectData.treeDefaultExpandedKeys =
    data.type === operateActionType.ADD ? ['0'] : [drawerInfo.record.parentAuthorityId]
  drawerInfo.selectProductId = data.type === operateActionType.ADD ? '' : data.record?.productId
  if (data.type === operateActionType.EDIT) {
    setFieldsValue({
      ...drawerInfo.record
    })
  }
})

const drawerReset = () => {
  treeSelectData.treeData = []
  treeSelectData.treeDefaultExpandedKeys = []
  resetFields()
  changeOkLoading(false)
  changeLoading(false)
}

const treeSelectChange = (value: string, label: string, extra: any) => {
  drawerInfo.selectProductId = extra.triggerNode?.props?.productId
}
// 提交数据
const confirmSubmit = async () => {
  try {
    await validate()
    let formValue = getFieldsValue()
    changeOkLoading(true)
    if (drawerInfo.type === operateActionType.ADD) {
      await authorityAdd({
        ...formValue,
        productId: drawerInfo.selectProductId,
        applicationId: drawerInfo.appId
      })
    } else if (drawerInfo.type === operateActionType.EDIT) {
      await authorityUpdate({
        ...formValue,
        productId: drawerInfo.selectProductId,
        authorityId: drawerInfo.record.authorityId,
        applicationId: drawerInfo.appId
      })
    }
    message.success(drawerInfo.type === operateActionType.ADD ? '权限新增成功' : '权限编辑成功')
    closeDrawer()
    drawerReset()
    emit('operateSuccess')
  } catch (error) {
    changeOkLoading(false)
  }
}
</script>

<style lang="less" scoped>
.box-drawer {
  padding: 8px 16px;
  :deep(.ant-form-item-label) {
    font-weight: 600;
  }
  :deep(.ant-input-number) {
    width: 100%;
  }
}
</style>
